<style lang="scss" scoped>
@import "@/assets/css/variable";
.activityShow {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  background-color: white;
  min-height: 100%;
  overflow: auto;
  box-sizing: border-box;
  .tocase {
    // position: fixed;
    // top: 0;
    // left: 0;
    // right: 0;
    background-color: rgb(255, 145, 0);
    color: white;
    padding: 0.8rem 1.6rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .powerdby {
    // position: fixed;
    // top: 0;
    // left: 0;
    // right: 0;
    padding: 0.8rem 1.6rem;
    text-align: center;
    text-decoration: underline;
    color: #666666;
  }
  .aaa{
	  color: #ff0004;
  }
  // .top{
  //   margin-top: 2.8rem;
  // }
  .info-box {
    padding: 1.8rem;
    border: 1px solid $border-c;
    .line1 {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .share-btn {
        display: flex;
        align-items: center;
        background-color: var(--theme_color);
        color: #fff;
        padding: 2px 5px;
        border-radius: 1rem;
      }
    }
    .line2 {
      margin-top: 1.2rem;
      display: flex;
      align-items: center;
    }
    .line3 {
      .fans-info {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .box-item {
          margin-top: 1.2rem;
          .cap-title {
            color: $color-subtitle;
            font-size: 1.4rem;
          }
          .num {
            margin-top: 0.4rem;
            font-size: 1.5rem;
            text-align: center;
          }
        }
      }
    }
  }
  .introduce {
    background-color: white;
    padding: 1.8rem;
  }
  .applyList {
    background-color: white;
    padding: 1.8rem;
    .table-header {
      display: flex;
      justify-content: space-between;
      font-size: 1.3rem;
      color: #222;
    }
    .table-content {
      display: flex;
      justify-content: space-between;
      font-size: 1.2rem;
      color: #333;
      padding-top: 1rem;
    }
  }
  .contact {
    background-color: white;
    padding: 1.8rem;
    .content {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      height: 9rem;
      .line {
        display: flex;
        align-items: center;
        span,
        a {
          margin-left: 1rem;
          font-size: 1.3rem;
        }
      }
    }
  }
  .show {
    height: auto;
    background-color: white;
    position: relative;
    .close-icon {
      position: absolute;
      width: 2.4rem;
      height: 2.4rem;
      right: 0.7rem;
      top: 0.7rem;
      border-radius: 1.2rem;
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 2;
    }
    img {
      width: 100%;
    }
    .posterHtml {
      // display: flex;
      #coverImg {
        display: flex;
        width: 100%;
        max-height: 30rem;
        object-fit: cover;
      }
      .imgBox {
        width: 100%;
      }
      .content {
        padding: 1.2rem;
        display: flex;
        height: 14rem;
        justify-content: space-between;
        .desc {
          word-wrap: break-word;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          height: 100%;
          .line1 {
            font-size: 2rem;
            font-weight: bold;
            color: #333;
            display: flex;
            align-items: center;
          }
          .line2 {
            font-size: 2.2rem;
            font-weight: 900;
            color: #111;
            // overflow: hidden;
            // text-overflow: ellipsis;
            // display: -webkit-box;
            // -webkit-line-clamp:2; /* 设置行数 */
            // -webkit-box-orient:vertical;
          }
        }
        .qrcode {
        }
      }
      .bottom-box {
        padding-bottom: 2rem;
        padding-left: 1.2rem;
        padding-right: 1.2rem;
      }
    }
  }
}
.imgBox {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba($color: #000000, $alpha: 0.98);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 3000;
  img {
    width: 100%;
  }
  .tips {
    color: white;
  }
  .close-icon {
    position: fixed;
    width: 2.4rem;
    height: 2.4rem;
    right: 0.7rem;
    top: 0.7rem;
    border-radius: 1.2rem;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 3002;
  }
}
.fix-bottom {
  position: fixed;
  bottom: 1rem;
  left: 0;
  right: 0;
  width: 100%;
  z-index: 3;
  box-sizing: border-box;
}
</style>
<template>
  <div class="activityShow" :style="{ '--theme_color': theme_color }">
	<van-skeleton :row="$store.state.skeletonRow" :loading="loadingSkeleton">
		<Header
		  :config="config" :backColor="theme_color"
		  v-show="activityItem.act_release == 1"
		></Header>
    
    <music-play v-if="activityItem.music" :activityItem="activityItem"></music-play>
		<div class="top">
		  <img :src="activityItem.cover" />
		</div>
		<div class="info-box line-height-l">
		  <div class="line1">
		    <div class="fs-18 t-bold color-ll">{{ activityItem.title }}</div>
		    <div class="share-btn" @click="shareBtn1">
		      <van-icon name="share-o" /><span class="share">分享</span>
		    </div>
		  </div>
		  <div class="line2">
		    <van-icon name="clock-o" /><span class="margL-m fs-12"
		      >报名截止到 {{ activityItem.end_time }}</span
		    >
		  </div>
		  <div class="line3" v-if="activityItem.join_num >= 6">
		    <div class="fans-info">
		      <div class="box-item">
		        <div class="cap-title">当前活动</div>
		        <div class="num">
		          {{ activityItem.status == 1 ? "报名中" : "已结束" }}
		        </div>
		      </div>
		      <div class="box-item">
		        <div class="cap-title">浏览数</div>
		        <div class="num">{{ activityItem.browse_num || 0 }}</div>
		      </div>
		      <div class="box-item">
		        <div class="cap-title">参与数</div>
		        <div class="num">{{ activityItem.join_num || 0.0 }}</div>
		      </div>
		    </div>
		  </div>
		</div>
		<div class="introduce line-height-l">
		  <div class="fs-18 t-bold margB-l color-ll">活动介绍</div>
		  <div v-for="item in activityItem.introduce" :key="Number(item.id)">
		    <div
		      v-if="item.type === 'text'"
		      class="margT-m line-height-l fs-12"
		      v-html="item.value"
		    ></div>
		    <img v-if="item.type === 'img'" :src="item.value" />
		  </div>
		</div>
		<div class="contact line-height-l">
		  <div class="fs-18 t-bold margB-l color-ll">联系方式</div>
		  <div class="content">
		    <div class="line">
		      <van-icon
		        name="shop"
		        size="1.5rem"
		        :color="theme_color"
		      />
		      <span>{{ activityItem.merchantname }}</span>
		    </div>
		    <div class="line">
		      <van-icon
		        name="phone-circle"
		        size="1.5rem"
		        :color="theme_color"
		      />
		      <a :href="`tel:${activityItem.mobile}`">{{ activityItem.mobile }}</a>
		    </div>
		    <div class="line">
		      <van-icon
		        name="location"
		        size="1.5rem"
		        :color="theme_color"
		      />
		      <span>{{ activityItem.address }}</span>
		    </div>
		  </div>
		</div>
    <!-- 分享蒙版 -->
    <share-mask v-if="cancelShow" @shareChange="shareChange" @cancelChange="cancelChange"></share-mask>

		<Footer :config="config"></Footer>
		<div class="tabbar-height"></div>
		<div class="tabbar-height"></div>
		<div class="fix-bottom padding-lr">
		  <van-button
		    v-if="is_apply"
		    type="danger"
		    size="normal"
			:color="theme_color"
		    plain
		    @click="toView('applyTrue')"
		    block
		    >已报名 查看凭证</van-button
		  >
		  <van-button
		    v-else
		    :color="theme_color"
		    size="normal"
		    block
		    @click="toView('applyFalse')"
		    >{{activityItem.status == 1? '我要报名': '活动结束'}}</van-button
		  >
		</div>
		<van-popup v-model="showPop" position="bottom" round>
		  <div class="show">
		    <span
		      class="close-icon"
		      :style="{ backgroundColor: theme_color }"
		      @click="showPop = false"
		      ><van-icon color="white" name="cross"
		    /></span>
		    <!-- 海报html元素 -->
		    <div id="posterHtml" class="posterHtml">
		      <img id="coverImg" :src="copyimg" />
		      <!-- <div id="imgBox"></div> -->
		      <div class="content">
		        <div class="desc">
		          <div class="line1">
		            <span>快来参加</span>
		            <van-icon class="margL-m" name="fire" :color="theme_color" />
		          </div>
		          <div class="line2">{{ activityItem.title }}</div>
		        </div>
		        <!-- 二维码 -->
		        <!-- <div class="qrcode" id="qrcode" ref="qrcode"></div> -->
		        <canvas class="qrcode" id="qrCode-canvas"></canvas>
		      </div>
		      <div class="margT-l bottom-box">
		        <div class="fs-16 t-bold">{{ activityItem.merchantname }}</div>
		        <div class="color-m margT-m" style="display:flex; center;">
		          <span></span>
		          <span>本次活动 {{ activityItem.end_time }} 结束</span>
		          <span></span>
		        </div>
		      </div>
		    </div>
		    <div class="padding-lr">
		      <van-button
		        :color="theme_color"
		        block
		        @click="createPoster"
		        :loading="createLoading"
		        >生成海报</van-button
		      >
		    </div>
		  </div>
		</van-popup>
		<div class="imgBox" v-if="showImgPop">
		  <img :src="createImg" />
		  <div class="tips margT-m fs-16">Tips:长按以上海报即可保存或转发</div>
		  <span
		    class="close-icon"
		    :style="{ backgroundColor: theme_color }"
		    @click="showImgPop = false"
		    ><van-icon color="white" name="cross"
		  /></span>
		</div>
	</van-skeleton>
  </div>
</template>

<script>
import { Button, Toast, Tab, Tabs, Icon, Dialog, Popup, Skeleton  } from "vant";
import QRCode from "qrcode";
import html2canvas from "html2canvas";
// import func from 'vue-editor-bridge';
// import utils from '@/assets/js/utils.js'
import Header from "@/components/header";
import Footer from "@/components/Footer";
import MusicPlay from "@/components/MusicPlay";
import ShareMask from "@/components/ShareMask";
import { mapGetters } from 'vuex'
export default {
  name: "applyActivityactivityShow",
  components: {
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Button.name]: Button,
    [Icon.name]: Icon,
    [Dialog.name]: Dialog,
    [Popup.name]: Popup,
	[Skeleton.name]: Skeleton,
    Header,
    Footer,
    MusicPlay,
    ShareMask
  },
  data() {
    return {
	  loadingSkeleton:true,
      activityItem: "",
      active: 0,
      openid: "",
      is_apply: false,
      posterImg: "",
      showPop: false,
      showImgPop: false,
      createLoading: false,
      id: "",
      thisItem: {},
      createImg: "",
      config: "",
      theme_color: '',
      copyimg: '',
      staff_id: null,
	  domain:{},
    cancelShow: false,
    };
  },
  // computed: {
  //   getOpenId() {
  //     this.openid = this.$store.state.openid
  //     return this.openid
  //   }
  // },
  created() {
  },
  computed: {
	  ...mapGetters(["getMasterColor"]),
	},
  mounted() {
    const _this = this;
    _this.activityItem = _this.$store.state.activityItem;
    _this.staff_id = _this.$route.query.staff_id;
    _this.getDomain()
    // 获取用户在后台管理系统中自定义的H5页面所显示的应用名称
    _this.ConfigItem();
  },
  methods: {
	  getDomain() {
	  	const _this = this;
	  	if (process.env.NODE_ENV == "production") {
	  		_this.openid = localStorage.getItem("COPENID");
	  		if(_this.$route.query.openid&&_this.$route.query.openid!='undefined'){
	  			_this.openid = _this.$route.query.openid
	  			localStorage.setItem("COPENID",_this.openid);
	  		}
	  	} else {
	  		_this.openid = _this.$store.state.openid;
	  	}
	  	let params = {};
	  	_this.$request.getDomain(params).then((res) => {
	  		if(res.ret==200) {
	  			if(res.data.value.mainUrl&&res.data.value.cannonUrl){
	  				let domain = {
	  					mainUrl:res.data.value.mainUrl,
	  					cannonUrl:res.data.value.cannonUrl
	  				}
	  				_this.domain = domain
	  				
	  				console.log("cannonUrl:"+location.href.indexOf(_this.domain.cannonUrl))
	  				if(location.href.indexOf(_this.domain.cannonUrl)>-1) {
	  					_this.openid = _this.$route.query.openid
	  					localStorage.setItem("COPENID",_this.openid);
	  					console.log('cannonUrl_this.openid',_this.openid)
	  				}
	  				//openid没拿到的时候
	  				if(!_this.openid||_this.openid=='undefined') {
	  					//当前为炮灰域名的时候
	  					if(location.href.indexOf(_this.domain.cannonUrl)>-1) {
	  						//跳转到主域名
	  						window.location.href = `${_this.domain.mainUrl}${
	  							location.href.indexOf("addons") > -1
	  							  ? "/addons/youmi_activitys/public"
	  							  : ""
	  						}/plugin/index.html#/caseShow/applyActivity/activityShow/${Number(_this.$route.params.id)}?staff_id=${_this.$route.query.staff_id}&p_openid=${_this.$route.query.p_openid}`;
							return;
	  					}
	  				}else{
	  					_this.toCannonUrl()
	  				}
	  			}
				console.log("_this.openid:"+_this.openid)
				if (!_this.openid || _this.openid == "undefined") {
				  _this.getWeixinConfig(); // 通过微信授权 获取 openID
				} else {
				  _this.getActivityItem(); // 获取活动数据的同时会调用getOrderItem、shareInit函数是、
				}
	  		}
	  	});
	  },
	  toCannonUrl() {
		  const _this = this;
		  if(_this.domain.mainUrl&&location.href.indexOf(_this.domain.mainUrl)>-1) {
			//跳转到炮灰域名
			window.location.href = `${_this.domain.cannonUrl}${
				location.href.indexOf("addons") > -1
				  ? "/addons/youmi_activitys/public"
				  : ""
			}/plugin/index.html#/caseShow/applyActivity/activityShow/${Number(_this.$route.params.id)}?staff_id=${_this.$route.query.staff_id}&p_openid=${_this.$route.query.p_openid}&openid=${_this.openid}`;
		  }
	  },
    // 分享按钮
    shareBtn1() {
      this.cancelShow = true
    },
    // 取消按钮
    cancelChange() {
      this.cancelShow = false
    },
    // 生成海报
    shareChange() {
      this.cancelShow = false
      this.shareBtn()
    },
    ConfigItem() {
      const _this = this;
      let params = {};
      _this.$request.ConfigItem(params).then((res) => {
        _this.config = res.data.value;
        console.log("_this.config", _this.config,'color',_this.config.color);
		_this.$store.commit('setMasterColor',_this.config.color)
      });
    },
    shareInit(activityItem) {
      const _this = this;
      const url = location.href.split("#")[0];
      let params = {
        url: url,
      };
      _this.$request.configJssdk(params).then((res) => {
        wx.config({
          debug: false, // 是否开启调试模式
          appId: res.data.appId, //appid
          timestamp: res.data.timestamp, // 时间戳
          nonceStr: res.data.nonceStr, // 随机字符串
          signature: res.data.signature, // 签名
          jsApiList: [
            "checkJsApi",
            "updateAppMessageShareData",
            "updateTimelineShareData",
          ], // 需要使用的JS接口列表
        });
		// let share_href = location.href // 这里需要处理herf，把里面的code给过滤掉
        let link = ''
        if(location.href.indexOf('staff_id') > -1) {
          link = location.href
        } else {
          link =  `${location.href}?staff_id=${this.staff_id}`
        }
        const dataShare = {
          title: activityItem.sharetitle,
          desc: activityItem.share_describe, // 分享描述
          link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: activityItem.shareimg, // 分享图标
          success: function () {
            // 设置成功
          },
          fail: function (error) {
            // alert(JSON.stringify(error))
          },
        };
        wx.updateAppMessageShareData(dataShare);
        wx.updateTimelineShareData(dataShare);
        wx.error(function (error) {
          // alert(JSON.stringify(error))
        });
      });
    },
    toTop() {
      let top = document.documentElement.scrollTop || document.body.scrollTop;
      // 实现滚动效果 
      const timeTop = setInterval(() => {
        document.body.scrollTop = document.documentElement.scrollTop = top -= 50;
        if (top <= 0) {
          clearInterval(timeTop);
        }
      }, 10);
    },
    shareBtn() {
      this.toTop()
      const _this = this;
      let params = {
        id: _this.activityItem.id,
      }
      _this.$request.getActivityItembase64(params).then(res => {
        _this.copyimg = res.data
      })
      _this.showPop = true;
      _this.$nextTick(function () {
        _this.createQrcode();
      });
    },
    createPoster() {
      // 生成海报
      const vm = this;
      vm.createLoading = true;
      const domObj = document.getElementById("posterHtml");
      html2canvas(domObj, {
        useCORS: true,
        allowTaint: true,
        logging: true,
        letterRendering: true,
        onclone(doc) {
          let e = doc.querySelector("#posterHtml");
          e.style.display = "block";
        },
      }).then(function (canvas) {
        // 在微信里,可长按保存或转发
        // let url = canvas.toDataURL('image/png')
        // const a = document.createElement('a'); // 创建a标签
        // a.setAttribute('download', `${new Date().getTime()}.png`);// download属性
        // a.setAttribute('href', url);// href链接
        // a.click();// 自执行点击事件
        let url = canvas.toDataURL("image/png");
        vm.createImg = url;
        vm.showImgPop = true;
        vm.createLoading = false;
        vm.showPop = false;
      });
    },
    createQrcode() {
      const _this = this;
      let href = `${location.protocol}//${location.hostname}${
        location.href.indexOf("addons") > -1
          ? "/addons/youmi_activitys/public"
          : ""
      }/plugin/index.html#/caseShow/${this.activityItem.model}/activityShow/${
        this.activityItem.id
      }?staff_id=${this.staff_id}`;
      
      let canvas = document.getElementById("qrCode-canvas");
      QRCode.toCanvas(canvas, href, (error) => {
        if (error) {
          console.log(error);
        } else {
          canvas.style.width = "12rem";
          canvas.style.height = "12rem";
          // _this.createPoster()
        }
      });
    },
    // 获取该活动的订单信息
    getOrderItem() {
      const _this = this;
      let params = {
        openid: _this.openid,
        activity_id: Number(this.$route.params.id),
      };
      _this.$request.getOrderItem(params).then((res) => {
        const orderItem = res.data;
        if (orderItem.openid == this.openid) {
          _this.is_apply = true;
        }
        console.log("-----orderItem-----", orderItem);
        _this.$store.commit("setOrderItem", orderItem);
        // 获取订单列表，并判断是否有自己的订单
        // let orderList = res.data.val
        // console.log('-----orderList-----',orderList)
        // orderList.forEach(item=>{
        // 	if(item.openid==_this.openid){
        // 		_this.is_apply = true
        // 	}
        // })
        //      if(res.data.val&&res.data.val!=null&&res.data.val.length>0){

        //        _this.is_apply = true
        //      }
      });
    },
    getWeixinConfig() {
      const _this = this;
      let params = {};
      _this.$request.getWeixinConfig(params).then((res) => {
        _this.$store.commit("setAppid", res.data.value.appid);
        _this.$store.commit("setSecret", res.data.value.secret);
        //_this.getCode(res.data.value.appid)
        _this.getCode(res.data.value.appid);
      });
    },
    getCode(appid) {
      // 非静默授权，第一次有弹框
      const _this = this;
      const code = this.getUrlParam("code"); // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
      const local = window.location.href;
      if (code == null || code === "") {
        window.location.href =
          "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
          appid +
          "&redirect_uri=" +
          encodeURIComponent(local) +
          "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
      } else {
        _this.$store.commit("setCode", code);
        _this.getOpenId(code); //把code传给后台获取用户信息
      }
    },
    getUrlParam(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
    getFansItem(item) {
      console.log("fansItem:", item);
      const _this = this;
      let params = {
        openid: item.openid || _this.openid,
        nickname: item.nickname,
        name: item.nickname,
        avatar: item.avatar,
        province: item.province,
        city: item.city,
      };
      console.log("item.openid", item.openid);
      console.log("fansItem:", item);
      _this.$request.getFansItem(params).then((res) => {
        // 默认
        // _this.getOrderItem();
      });
    },
    getOpenId(code) {
      const _this = this;
      let params = {
        appid: _this.$store.state.appid,
        secret: _this.$store.state.secret,
        code: code,
      };
	  //app.weixin.weixin
      _this.$request.getOpenid(params).then((res) => {
		if(res.data[0] && res.data[0] == 1){
			//这里需进行页面跳转，把当前链接中的code信息给过滤掉
			const url = (location.href)
			window.location.href = `${url.split('?')[0]}#${url.split('#')[1]}`
		}else{
			const userInfo = res.data[0];
			// alert('userInfo:'+JSON.stringify(userInfo))
			const openid = userInfo.openid;
			_this.openid = openid;
			const nickname = userInfo.nickname;
			const headimgurl = userInfo.headimgurl;
			const province = userInfo.province;
			const city = userInfo.city;
			// const headimgurl = userInfo["headimgurl"];
			// const headimgurl = userInfo["headimgurl"];
			// const unionid = res.data.unionid;
			_this.$store.commit("setOpenid", openid);
			localStorage.setItem("COPENID", openid);
			// alert('COPENID:'+openid)
			const item = {
			  openid,
			  nickname,
			  avatar: headimgurl,
			  province,
			  city,
			  name: nickname,
			};
			_this.$store.commit("setUserInfo", item);
			localStorage.setItem("USERINFO", JSON.stringify(item));
			_this.getFansItem(item);
			_this.getActivityItem();
			_this.toCannonUrl()
		}
      });
    },
    judgeIsApply() {
      const _this = this;
      const apply_list = _this.activityItem.apply_list;
      // _this.openid = "111"
      const isApply = apply_list.some((res) => res.openid == _this.openid);
      this.activityItem.is_apply = isApply;
    },
    getActivityItem() {
      const _this = this;
      const toast = Toast.loading({
        forbidClick: true,
        message: "加载中...",
      });
      let params = {
        id: Number(_this.$route.params.id),
        openid: _this.openid,
      };
      _this.$request.getActivityItem(params).then((res) => {
        _this.activityItem = res.data;
        _this.theme_color = res.data.theme_color;
        if (_this.activityItem) {
          _this.getOrderItem();
          _this.shareInit(_this.activityItem);
          _this.getMerchantItem(_this.activityItem.merchant_id);
        }
        _this.$store.commit("setActivityItem", _this.activityItem);
        document.title = _this.activityItem.title;
        toast.clear();
		this.loadingSkeleton = false;
      });
    },
    // 获取商户
    getMerchantItem(merchant_id) {
      let params = {
        id: merchant_id,
      };
      this.$request.getMerchantItema(params).then((res) => {
        this.door_header = res.data.door_header;
        this.$store.commit("setMerchant", res.data);
      });
    },
    toCaseView() {
      window.location.href = `//${location.hostname}${location.href.indexOf('addons')>-1 ? '/addons/youmi_activitys/public' : ''}/mobile/index.html`;
    },
    toView(to) {
      if(to=="applyTrue"){
        if (this.activityItem.status == 2)  return this.$toast("活动已结束");
        this.$store.commit("setThemeColor", this.theme_color);
        this.$router.push(`/caseShow/applyActivity/applyPZ?staff_id=${this.staff_id}`);
      }else{
        if (this.activityItem.status == 2)  return this.$toast("活动已结束");
        this.$store.commit("setThemeColor", this.theme_color);
        this.$router.push(`/caseShow/applyActivity/applyForm?staff_id=${this.staff_id}`);
      }
    },
  },
};
</script>